package com.link.base.base.esb.controller;

import com.link.base.base.contract.model.BillInfo;
import com.link.base.base.contract.model.ReturnInfo;
import com.link.base.base.contract.service.ContractService;
import com.link.base.base.contract.service.ModContractService;
import com.link.base.base.contract.service.PriContraSignService;
import com.link.base.base.esb.model.*;
import com.link.base.base.esb.service.LinkBaseDataApiService;
import com.link.base.base.projectmanage.service.CarRegisterService;
import com.link.base.core.basic.util.ApiUtil;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.util.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 基础数据restful接口
 *
 * @author: liuqixin
 * @date: 2020/08/19 13:57
 */
@RestController
@RequestMapping("/link/api/data")
public class LinkBaseDataApiController {

    private static final Logger logger = LogManager.getLogger(LinkBaseDataApiController.class);

    @Resource
    private LinkBaseDataApiService linkBaseDataApiService;

    @Resource
    private KeyGenerateService keyGenerateService;

    @Resource
    private ModContractService modContractService;

    @Resource
    private PriContraSignService priContraSignService;

    @Resource
    private ContractService contractService;

    @Resource
    private CarRegisterService carRegisterService;

    /**
     * 接受ESB数据，保存员工信息
     *
     * @author 刘启鑫
     * @date 2020/8/19 15:22
     */
    @RequestMapping(value = "/employee", method = RequestMethod.POST)
    public ApiResponse upsertEmployeeFromESB(@RequestBody EmployeeRequestBody employeeRequestBody) {
        EsbInfo response = null;
        EsbInfo esbInfo = employeeRequestBody.getEsbInfo();
        EmployeeDTO requestInfo = employeeRequestBody.getRequestInfo();
        // EsbInfo非空时，设置对应ID
        setEsbInfoInstId(esbInfo);
        logger.info("员工基础数据接口 -> URL:/link/api/data/employee -> 接收数据：{}", employeeRequestBody);

        try {
            response = linkBaseDataApiService.upsertForESB(esbInfo, requestInfo);
        } catch (Exception e) {
            logger.error("LinkBaseDataApiService -> upsertForESB:"
                    + "[参数]：esbInfo: {},requestInfo: {} ;"
                    + "[异常]: {} ,异常信息: {} ;", esbInfo, requestInfo, e, e.getMessage());
            // 遇见未知报错时，返回默认编码
            esbInfo.setReturnCodeMsg(EsbInfo.E0999)
                    .setReturnStatus(EsbInfo.RT_STATUS_ERROR)
                    .setAttr1(e.getMessage());
            response = esbInfo;
        }
        response.setResponseTime(ApiUtil.getCurrentDetailTime());
        ApiResponse apiResponse = getApiResponse(response);
        logger.info("员工基础数据接口 -> URL:/link/api/data/employee -> 返回信息：{}", apiResponse);
        return apiResponse;
    }


    @RequestMapping(value = "/orgnization", method = RequestMethod.POST)
    public ApiResponse upsertOrgnizationFromESB(@RequestBody OrgnizationRequestBody orgnizationRequestBody) {
        EsbInfo response = null;
        EsbInfo esbInfo = orgnizationRequestBody.getEsbInfo();
        OrgnizationDTO requestInfo = orgnizationRequestBody.getRequestInfo();

        // EsbInfo非空时，设置对应ID
        setEsbInfoInstId(esbInfo);
        logger.info("");
        logger.info("组织基础数据接口 -> URL:/link/api/data/orgnization -> 接收数据：{}", orgnizationRequestBody);
        try {
            response = linkBaseDataApiService.upsertForESB(esbInfo, requestInfo);
        } catch (Exception e) {
            logger.error("LinkBaseDataApiService -> upsertForESB:"
                    + "[参数]：esbInfo: {},requestInfo: {} ;"
                    + "[异常]: {} ,异常信息: {} ;", esbInfo, requestInfo, e, e.getMessage());
            // 遇见未知报错时，返回默认编码
            esbInfo.setReturnCodeMsg(EsbInfo.E0999)
                    .setReturnStatus(EsbInfo.RT_STATUS_ERROR)
                    .setAttr1(e.getMessage());
            response = esbInfo;
        }
        response.setResponseTime(ApiUtil.getCurrentDetailTime());

        ApiResponse apiResponse = getApiResponse(response);
        logger.info("组织基础数据接口 -> URL:/link/api/data/orgnization -> 返回信息：{}", apiResponse);
        return apiResponse;
    }

    @RequestMapping(value = "/position", method = RequestMethod.POST)
    public ApiResponse upsertPositionFromESB(@RequestBody PositionRequestBody positionRequestBody) {
        EsbInfo response = null;
        EsbInfo esbInfo = positionRequestBody.getEsbInfo();
        PositionDTO requestInfo = positionRequestBody.getRequestInfo();
        // EsbInfo非空时，设置对应ID
        setEsbInfoInstId(esbInfo);
        logger.info("职位基础数据接口 -> URL:/link/api/data/position -> 接收数据：{}", positionRequestBody);

        try {
            response = linkBaseDataApiService.upsertForESB(esbInfo, requestInfo);
        } catch (Exception e) {
            logger.error("LinkBaseDataApiService -> upsertForESB:"
                    + "[参数]：esbInfo: {},requestInfo: {} ;"
                    + "[异常]: {} ,异常信息: {} ;", esbInfo, requestInfo, e, e.getMessage());
            // 遇见未知报错时，返回默认编码
            esbInfo.setReturnCodeMsg(EsbInfo.E0999)
                    .setReturnStatus(EsbInfo.RT_STATUS_ERROR)
                    .setAttr1(e.getMessage());
            response = esbInfo;
        }
        response.setResponseTime(ApiUtil.getCurrentDetailTime());
        ApiResponse apiResponse = getApiResponse(response);
        logger.info("职位基础数据接口 -> URL:/link/api/data/position -> 返回信息：{}", apiResponse);
        return apiResponse;
    }

    @RequestMapping(value = "/billInfo", method = RequestMethod.POST)
    public ApiResponse upsertBillInfoFromESB(@RequestBody BillInfoBody billInfoBody) {
        EsbInfo response = null;
        EsbInfo esbInfo = billInfoBody.getEsbInfo();
        BillInfo requestInfo = billInfoBody.getRequestInfo();
        // EsbInfo非空时，设置对应ID
        setEsbInfoInstId(esbInfo);
        logger.info("开票信息数据接口 -> URL:/link/api/data/billInfo -> 接收数据：{}", billInfoBody);

        try {
            response = linkBaseDataApiService.upsertForESB(esbInfo, requestInfo);
        } catch (Exception e) {
            logger.error("LinkBaseDataApiService -> upsertForESB:"
                    + "[参数]：esbInfo: {},requestInfo: {} ;"
                    + "[异常]: {} ,异常信息: {} ;", esbInfo, requestInfo, e, e.getMessage());
            // 遇见未知报错时，返回默认编码
            esbInfo.setReturnCodeMsg(EsbInfo.E0999)
                    .setReturnStatus(EsbInfo.RT_STATUS_ERROR)
                    .setAttr1(e.getMessage());
            response = esbInfo;
        }
        response.setResponseTime(ApiUtil.getCurrentDetailTime());
        ApiResponse apiResponse = getApiResponse(response);
        logger.info("开票信息数据接口 -> URL:/link/api/data/position -> 返回信息：{}", apiResponse);
        return apiResponse;
    }

    @RequestMapping(value = "/returnInfo", method = RequestMethod.POST)
    public ApiResponse upsertReturnInfoFromESB(@RequestBody ReturnInfoBody returnInfoBody) {
        EsbInfo response = null;
        EsbInfo esbInfo = returnInfoBody.getEsbInfo();
        ReturnInfo requestInfo = returnInfoBody.getRequestInfo();
        // EsbInfo非空时，设置对应ID
        setEsbInfoInstId(esbInfo);
        logger.info("开票信息数据接口 -> URL:/link/api/data/billInfo -> 接收数据：{}", returnInfoBody);

        try {
            response = linkBaseDataApiService.upsertForESB(esbInfo, requestInfo);
        } catch (Exception e) {
            logger.error("LinkBaseDataApiService -> upsertForESB:"
                    + "[参数]：esbInfo: {},requestInfo: {} ;"
                    + "[异常]: {} ,异常信息: {} ;", esbInfo, requestInfo, e, e.getMessage());
            // 遇见未知报错时，返回默认编码
            esbInfo.setReturnCodeMsg(EsbInfo.E0999)
                    .setReturnStatus(EsbInfo.RT_STATUS_ERROR)
                    .setAttr1(e.getMessage());
            response = esbInfo;
        }
        response.setResponseTime(ApiUtil.getCurrentDetailTime());
        ApiResponse apiResponse = getApiResponse(response);
        logger.info("开票信息数据接口 -> URL:/link/api/data/position -> 返回信息：{}", apiResponse);
        return apiResponse;
    }

    /**
     * 设置EsbInfo的流水ID
     *
     * @param esbInfo
     */
    private void setEsbInfoInstId(EsbInfo esbInfo) {
        if (!Objects.isNull(esbInfo) && StringUtils.isBlank(esbInfo.getInstId())) {
            esbInfo.setInstId(keyGenerateService.keyGenerate().toString());
        }
    }

    /**
     * 返回报文转换
     *
     * @param esbInfo
     * @return
     */
    ApiResponse getApiResponse(EsbInfo esbInfo) {
        return new ApiResponse(esbInfo);
    }
}
